package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @文件名: LogRecordAspct
 * @作者: DX
 * @创建日期: 2025/10/17
 * @描述:
 */
@Slf4j
@Aspect
@Component
public class LogRecordAspct {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) {
        Object returnValue = null;

        try {

            long startTime = System.currentTimeMillis();

            returnValue = pjp.proceed();

            long endTime = System.currentTimeMillis();

            Object[] args = pjp.getArgs();


            OperateLog  operateLog = OperateLog.builder()
                    .className( pjp.getTarget().getClass().getName())
                    .operateUserId(CurrentUserContextHolders.get())
                    .returnValue(JSONUtil.toJsonStr(args))
                    .methodParams(JSONUtil.toJsonStr(returnValue))
                    .operateTime(LocalDateTime.now())
                    .costTime(endTime - startTime)
                    .build();

            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("写入失败", e);
                returnValue = Result.success("操作失败");
            }

        } catch (Throwable e) {
            returnValue = Result.success("操作失败");
            log.error("操作失败", e);
        }
        return returnValue;
    }
}
